<?php
error_reporting(0);
$minPHPVersion = '5.2.0';

// ----------------------------- detect language ------------------------------
$supportedLanguages = array('en', 'cs', 'sk');
if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
    $langs = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
    foreach ($langs as &$lang) {
        $lang = explode(';', $lang);
        if (isset($lang[1])) {
            $lang[1] = explode('=', $lang[1]);
            $lang[1] = (float) $lang[1][1];
        } else {
            $lang[1] = 1;
        }
    }
    while (count($langs) > 0) {
        $priority = 0;
        foreach ($langs as &$lang) {
            if ($lang[1] > $priority) {
                $priority = $lang[1];
            }
        }
        for ($i = count($langs) - 1; $i >= 0; $i--) {
            if ($langs[$i][1] == $priority) {
                $found = array_search($langs[$i][0], $supportedLanguages);
                if ($found !== false) {
                    $language = $langs[$i][0];
                    $langs = array();
                    break;
                }
                array_splice($langs, $i, 1);
            }
        }
    }
    if (!isset($language)) {
        $language = 'en';
    }
} else {
    $language = 'en';
}

// --------------------------- localization strings ---------------------------
$l = array();
if ($language == 'en') {
    $l['OK'] = 'OK';
    $l['addWritePermissionForIndex'] = 'Failed. Please add write permission rights for index.php';
    $l['addWritePermissionForDir'] = 'Failed. Please add write permission rights to the root web directory';
    $l['phpVersion'] = "PHP version at least $minPHPVersion is required:" . phpversion();
    $l['zipSupport'] = 'Sorry, ZIP support is required by installer and updator';
    $l['gdVersion'] = 'Version 2.0 is required at least, found ' . GD_VERSION;
    $l['gdNotFound'] = 'GD not found';
    $l['safeMode'] = 'Safe mode has to be disabled';
    $l['magickQuotes'] = 'The magick_quotes_runtine has to be turned off';
    $l['notEnoughSpace'] = 'Not enough space on the hard drive';
    $l['cannotCreatePackage'] = 'Cannot create package file for extraction';
    $l['cannotReadInstaller'] = 'Cannot read the installer file';
    $l['cannotOpenPackage'] = 'Could not open extracted application package';
    $l['extractionFailed'] = 'Extraction of application package failed';
    $l['cannotRemovePackage'] = 'Could not remove application package';
    $l['glob'] = 'Glob not found';
    $l['pageTitle'] = 'WinterBreath CMS Installer';
    $l['h1'] = 'WinterBreath CMS Installer';
    $l['breadcrumbInstall'] = 'Installation';
    $l['breadcrumbExtraction'] = 'Extraction';
    $l['titleExtraction'] = 'Extraction';
    $l['initializing'] = 'Initializing the installer...';
    $l['progress'] = 'Installation progress';
    $l['extraction'] = 'Extraction';
    $l['settings'] = 'Settings';
    $l['completed'] = 'Completion';
    $l['testingWrite'] = 'Testing write permissions... ';
    $l['testingPhpVersion'] = 'Testing PHP version... ';
    $l['testingZip'] = 'Testing ZIP archives support... ';
    $l['testingGd'] = 'Checking GD version... ';
    $l['testingSafe'] = 'Checking safe mode... ';
    $l['testingMagickQuotes'] = 'Checking runtime magick quotes... ';
    $l['testingGlob'] = 'Checking for glob... ';
    $l['prepareExtraction'] = 'Preparing extraction... ';
    $l['extractingApp'] = 'Extracting application... ';
    $l['willBeRunIn'] = 'The application will be run in <span>3</span> seconds';
    $l['communicationError'] = 'Server/client communication error. Please try again.';
    $l['clickToShowDetails'] = '+ Click here to show details';
} elseif ($language == 'cs') {
    $l['OK'] = 'OK';
    $l['addWritePermissionForIndex'] = 'Chyba. Přidejte souboru index.php práva pro zápis';
    $l['addWritePermissionForDir'] = 'Chyba. Přidejte kořenovému adresáři práva pro zápis';
    $l['phpVersion'] = "Verze PHP musí být alespoň $minPHPVersion, ale je:" . phpversion();
    $l['zipSupport'] = 'Promiňte, ale instalátor vyžaduje podporu ZIP souborů';
    $l['gdVersion'] = 'Je vyžadována verze 2.0, nalezena ' . GD_VERSION;
    $l['gdNotFound'] = 'GD nebylo nazeleno';
    $l['safeMode'] = 'Safe mode musí být vypnut';
    $l['magickQuotes'] = 'Nastavení magick_quotes_runtine musí být vypnuté';
    $l['notEnoughSpace'] = 'Nedostatek místa na disku';
    $l['cannotCreatePackage'] = 'Není možné vytvořit balíček pro extrakci';
    $l['cannotReadInstaller'] = 'Není možné číst soubor instalátoru';
    $l['cannotOpenPackage'] = 'Není možné otevřít instalační balíček';
    $l['extractionFailed'] = 'Rozbalení instalačního balíčku selhalo';
    $l['cannotRemovePackage'] = 'Není možné odstranit instalační balíček';
    $l['glob'] = 'Glob funkce není povolena';
    $l['pageTitle'] = ' Instalátor WinterBreath CMS';
    $l['h1'] = 'Instalátor WinterBreath CMS';
    $l['breadcrumbInstall'] = 'Instalace';
    $l['breadcrumbExtraction'] = 'Rozbalení';
    $l['titleExtraction'] = 'Rozbalení';
    $l['initializing'] = 'Inicializace instalátoru...';
    $l['progress'] = 'Průběh instalace';
    $l['extraction'] = 'Rozbalení';
    $l['settings'] = 'Nastavení';
    $l['completed'] = 'Dokončení';
    $l['testingWrite'] = 'Kontrola práv zápisu... ';
    $l['testingPhpVersion'] = 'Test verze PHP... ';
    $l['testingZip'] = 'Test podpory ZIP souborů... ';
    $l['testingGd'] = 'Test verze GD... ';
    $l['testingSafe'] = 'Test nastavení safe mode... ';
    $l['testingMagickQuotes'] = 'Test nastavení runtime magick quotes... ';
    $l['testingGlob'] = 'Test podpory glob... ';
    $l['prepareExtraction'] = 'Příprava rozbalení... ';
    $l['extractingApp'] = 'Rozbalování... ';
    $l['willBeRunIn'] = 'Aplikace bude spuštěna za <span>3</span> vteřiny';
    $l['communicationError'] = 'Chyba při komunikaci se serverem. Zkuste to prosím znovu.';
    $l['clickToShowDetails'] = '+ Klikněte zde pro zobrazení detailů';
} elseif ($language == 'sk') {
    $l['OK'] = 'OK';
    $l['addWritePermissionForIndex'] = 'Chyba. Pridajte súboru index.php práva pre zápis';
    $l['addWritePermissionForDir'] = 'Chyba. Pridajte koreňovému priečinku práva pre zápis';
    $l['phpVersion'] = "Verzia PHP musí byť aspoň $minPHPVersion, ale je:" . phpversion();
    $l['zipSupport'] = 'Prepáčte, ale inštalátor vyžaduje podporu ZIP súborov';
    $l['gdVersion'] = 'Je vyžadovaná verze 2.0, nájdená ' . GD_VERSION;
    $l['gdNotFound'] = 'GD nebolo nájdené';
    $l['safeMode'] = 'Safe mode musí byť vypnutý';
    $l['magickQuotes'] = 'Nastavenie magick_quotes_runtine musí byť vypnuté';
    $l['notEnoughSpace'] = 'Nedostatok miesta na disku';
    $l['cannotCreatePackage'] = 'Nie je možné vytvoriť balíček pre extrakciu';
    $l['cannotReadInstaller'] = 'Nie je možné čítať súbor inštalátoru';
    $l['cannotOpenPackage'] = 'Nie je možné otvoriť inštalačný balíčok';
    $l['extractionFailed'] = 'Rozbalenie inštalačného balíčku zlyhalo';
    $l['cannotRemovePackage'] = 'Nie je možné odstrániť inštalačný balíčok';
    $l['glob'] = 'Glob funkcia nie je povolená';
    $l['pageTitle'] = 'Inštalácia CMS WinterBreath CMS';
    $l['h1'] = 'Inštalácia CMS WinterBreath';
    $l['breadcrumbInstall'] = 'Inštalácia';
    $l['breadcrumbExtraction'] = 'Rozbalenie';
    $l['titleExtraction'] = 'Rozbalenie';
    $l['initializing'] = 'Inicializáce inštalátoru...';
    $l['progress'] = 'Priebeh inštalácie';
    $l['extraction'] = 'Rozbalenie';
    $l['settings'] = 'Nastavenie';
    $l['completed'] = 'Dokončenie';
    $l['testingWrite'] = 'Kontrola práv zápisu... ';
    $l['testingPhpVersion'] = 'Test verzie PHP... ';
    $l['testingZip'] = 'Test podpory ZIP súborov... ';
    $l['testingGd'] = 'Test verzie GD... ';
    $l['testingSafe'] = 'Test nastavenia safe mode... ';
    $l['testingMagickQuotes'] = 'Test nastavenia runtime magick quotes... ';
    $l['testingGlob'] = 'Test podpory glob... ';
    $l['prepareExtraction'] = 'Príprava rozbalenia... ';
    $l['extractingApp'] = 'Rozbaľovanie... ';
    $l['willBeRunIn'] = 'Aplikácia bude spustená za <span>3</span> sekúnd';
    $l['communicationError'] = 'Chyba pri komunikácii so serverom. Skúste to prosím znovu.';
    $l['clickToShowDetails'] = '+ Kliknite sem pre zobrazenie detailov';
}

// ------------------------- installer application logic ----------------------
if (isset($_GET['action'])) {
    if ($_GET['action'] == 'writePermissions') {
        if (is_writable(dirname(__FILE__))) {
            if (is_writable(__FILE__)) {
                echo OK();
            } else {
                echo fail('addWritePermissionForIndex');
            }
        } else {
            echo fail('addWritePermissionForDir');
        }
    } elseif ($_GET['action'] == 'phpVersion') {
        if (phpversion() > $minPHPVersion) {
            echo OK();
        } else {
            echo fail('phpVersion');
        }
    } elseif ($_GET['action'] == 'zip') {
        if (class_exists('ZipArchive')) {
            echo OK();
        } else {
            echo fail('zipSupport');
        }
    } elseif ($_GET['action'] == 'gd') {
        if (function_exists('gd_info')) {
            if (GD_VERSION < '2.0.') {
                echo fail('gdVersion');
            } else {
                echo OK();
            }
        } else {
            echo fail('gdNotFound');
        }
    } elseif ($_GET['action'] == 'safeMode') {
        if (ini_get('safe_mode')) {
            echo fail('safeMode');
        } else {
            echo OK();
        }
    } elseif ($_GET['action'] == 'magicQuotes') {
        if (function_exists('get_magic_quotes_runtime') &&
                get_magic_quotes_runtime()) {
            echo fail('magickQuotes');
        } else {
            echo OK();
        }
    } elseif ($_GET['action'] == 'prepare') {
        $free = disk_free_space(dirname(__FILE__));
        $thisFile = filesize(__FILE__);
        if ($free < $thisFile * 3) {
            echo fail('notEnoughSpace');
        } else {
            $zip = fopen(dirname(__FILE__) . '/pack.zip', 'wb');
            if (!is_resource($zip)) {
                echo fail('cannotCreatePackage');
                exit;
            }
            $thisFile = fopen(__FILE__, 'rb');
            if (!is_resource($thisFile)) {
                echo fail('cannotReadInstaller');
                exit;
            }
            $barrier = true;
            $buffer = '';
            while (!feof($thisFile)) {
                $buffer .= fread($thisFile, 4096);
                if ($barrier) {
                    if (strpos($buffer, '//FILEEND' . '?>') !== false) {
                        $buffer = substr($buffer,
                                strpos($buffer, '//FILEEND' . '?>') + 11);
                        $barrier = false;
                    } else {
                        $buffer = '';
                    }
                }
            }
            fwrite($zip, base64_decode($buffer));
            fclose($zip);
            fclose($thisFile);
            echo OK();
        }
    } elseif ($_GET['action'] == 'extract') {
        try {
            $zip = new ZipArchive();
            if (!$zip->open(dirname(__FILE__) . '/pack.zip')) {
                echo fail('cannotOpenPackage');
                exit;
            }
            if (!$zip->extractTo(dirname(__FILE__))) {
                echo fail('extractionFailed');
                exit;
            }
            $zip->close();
            if (!unlink(dirname(__FILE__) . '/pack.zip')) {
                echo fail('cannotRemovePackage');
                exit;
            }
        } catch (Exception $e) {
            echo fail($e->getMessage());
            exit;
        }
        echo OK();
    } elseif ($_GET['action'] == 'glob') {
        if (function_exists('glob')) {
            echo OK();
        } else {
            echo fail('glob');
        }
    }
} elseif (count($_GET) == 0) {
    // -------------------------- main template -------------------------------
    ?><!DOCTYPE html>
<html>
    <head>
        <title><?php echo $l['pageTitle'] ?></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <link rel="stylesheet" type="text/css" href="?file=style" media="all" />
        <!--[if gte IE 9]>
        <style type="text/css">
            .gradient {
            filter: none;
            }
        </style>
        <![endif]-->
        <script type="text/javascript" src="?file=js"></script>
    </head>
    <body>
        <div id="base">
            <div id="border">
                <div id="header">
                    <h1><?php echo $l['h1'] ?></h1>
                    <h2>&nbsp;</h2>
                </div>
                <div id="breadcrumbs">
                    <a href="#" onclick="return false;"><?php echo $l['breadcrumbInstall'] ?></a> &middot;
                    <?php echo $l['breadcrumbExtraction'] ?>
                </div>
                <div id="content">
                    <div id="left">
                        <h2><?php echo $l['titleExtraction'] ?></h2>
                        
                        <div class="progress-bar">
                            <div id="progress"></div>
                        </div>
                        
                        <p id="msg" class="collapsed">
                            <span id="collapsed-error"></span>
                            <a href="#" onclick="var msg = document.getElementById('msg'); msg.className = ''; msg.style.height = ''; return false;">
                                <?php echo $l['clickToShowDetails'] ?>
                            </a>
                            <?php echo $l['initializing'] ?>
                        </p>
                    </div>
                    <div id="right">
                        <h2><?php echo $l['progress'] ?></h2>
                        <ul>
                            <li><strong>&raquo; <?php echo $l['extraction'] ?></strong></li>
                            <li><?php echo $l['settings'] ?></li>
                            <li><?php echo $l['completed'] ?></li>
                        </ul>
                    </div>
                    <div class="clear"></div>
                </div>
            </div>
        </div>
    </body>
</html><?php
} elseif (isset($_GET['file']) && ($_GET['file'] == 'style')) {
    // ----------------------- main css ---------------------------------------
header('Content-type: text/css; charset=UTF-8');
    ?>
* {
    margin: 0;
    padding: 0;
}

body {
    font: .74em "Trebuchet MS" Verdana, Arial, sans-serif;
}

#base {
    width: 696px;
    margin: 27px auto;
}

#border {
    border: 2px solid #bbb;
    border-radius: 15px;
    box-shadow: 0 0 15px #aaa;
    padding: 21px 24px;
}

#header {
    background: #85acf7;
    height: 66px;
    padding: 17px;
    color: #fff;
    /* gradients */
    background: #85acf7; /* Old browsers */
    /* IE9 SVG, needs conditional override of 'filter' to 'none' */
    background: url();
    background: -moz-linear-gradient(top, #85acf7 0%, #6695ed 100%); /* FF3.6+ */
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#85acf7), color-stop(100%,#6695ed)); /* Chrome,Safari4+ */
    background: -webkit-linear-gradient(top, #85acf7 0%,#6695ed 100%); /* Chrome10+,Safari5.1+ */
    background: -o-linear-gradient(top, #85acf7 0%,#6695ed 100%); /* Opera 11.10+ */
    background: -ms-linear-gradient(top, #85acf7 0%,#6695ed 100%); /* IE10+ */
    background: linear-gradient(top, #85acf7 0%,#6695ed 100%); /* W3C */
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#85acf7', endColorstr='#6695ed',GradientType=0 ); /* IE6-8 */
}

h1 {
    font-size: 1.9em;
    line-height: 1.2em;
}

h2 {
    font-size: 1.3em;
}

#breadcrumbs {
    background: #F6F9FB;
    border-bottom: 1px solid #E1E1E1;
    height: 17px;
    padding: 5px;
}

a {
    text-decoration: none;
    color: #3B6EBF;
}

#content {
    padding: 15px;
}

#left {
    width: 456px;
    float: left;
    text-align: justify;
    padding-right: 15px;
}

#right {
    width: 140px;
    float: left;
}

.clear {
    clear: both;
}

#content h2 {
    color: #3B6EBF;
    font-size: 1.4em;
}

#right ul {
    margin: 19px 26px;
    list-style: square;
    color: #3B6EBF;
}

#right ul li {
    margin: 4px 0;
}

#left h2 {
    margin-bottom: 15px;
}

#right h2 {
    font-size: 1.2em;
    margin-top: 6px;
    margin-left: 6px;
}

.error {
    color: #c70000;
}

.confirm {
    color: #00ad00;
}

#msg a, #msg #collapsed-error {
    display: none;
}

#msg.collapsed a, #msg.collapsed #collapsed-error {
    display: block;
}

#msg.collapsed {
    height: 20px;
    overflow: hidden;
}

.progress-bar {
    height: 20px;
    border: 1px solid #3B6EBF;
    border-radius: 5px;
    overflow: hidden;
}

#progress {
    height: 20px;
    background: #3B6EBF;
    width: 98%;
}
    <?php
} elseif (isset($_GET['file']) && ($_GET['file'] == 'js')) {
    // ------------------------ JS logic --------------------------------------
header('Content-type: text/javascript; charset=UTF-8');
    ?>
(function () {
var msg, init, checkWrite, ajax, step2, step3, step4, step5, step6,
        step9, step10, step11, step12, setProgress;

init = function () {
    msg = document.getElementById('msg');
    msg.innerHTML += '<br /><?php echo $l['testingWrite'] ?>';
    ajax('writePermissions', step2);
    setProgress(5);
};

step2 = function () {
    msg.innerHTML += '<?php echo $l['testingPhpVersion'] ?>';
    ajax('phpVersion', step3);
    setProgress(10);
};

step3 = function () {
    msg.innerHTML += '<?php echo $l['testingZip'] ?>';
    ajax('zip', step4);
    setProgress(15);
};

step4 = function () {
    msg.innerHTML += '<?php echo $l['testingGd'] ?>';
    ajax('gd', step5);
    setProgress(20);
};

step5 = function () {
    msg.innerHTML += '<?php echo $l['testingSafe'] ?>';
    ajax('safeMode', step6);
    setProgress(25);
};

step6 = function () {
    msg.innerHTML += '<?php echo $l['testingMagickQuotes'] ?>';
    ajax('magicQuotes', step9);
    setProgress(30);
};

step9 = function () {
    msg.innerHTML += '<?php echo $l['testingGlob'] ?>';
    ajax('glob', step10);
    setProgress(35);
};

step10 = function () {
    msg.innerHTML += '<?php echo $l['prepareExtraction'] ?>';
    ajax('prepare', step11);
    setProgress(40);
};

step11 = function () {
    msg.innerHTML += '<?php echo $l['extractingApp'] ?>';
    ajax('extract', step12);
    setProgress(60);
};

step12 = function () {
    var i, interval;
    i = 6; // 6 * 500ms = 6 seconds
    msg.innerHTML += '<?php echo $l['willBeRunIn'] ?>';
    setProgress(80);
    interval = setInterval(function () {
        i--;
        document.getElementsByTagName('span')[1].innerHTML = Math.ceil(i / 2);
        setProgress(88 + (12 - i * 3));
        if (i == 0) {
            clearInterval(interval);
            location.reload();
        }
    }, 500);
};

setProgress = function (progress) {
    document.getElementById('progress').style.width = progress + '%';
};

ajax = function (action, callback) {
    var xhr;
    xhr = window.XMLHttpRequest ? new XMLHttpRequest() :
            new ActiveXObject("Microsoft.XMLHTTP");
    xhr.onreadystatechange = function () {
        var response;
        if (xhr.readyState != 4) {
            return;
        }
        if (xhr.status == 200) {
            response = xhr.responseText;
            response = response.split('|', 2);
            msg.innerHTML += response[1];
            if (response[0] == 1) {
                callback();
            } else {
                document.getElementById('collapsed-error').innerHTML =
                        response[1];
                if (msg.className) {
                    msg.style.height = '40px';
                }
            }
        } else {
            msg.innerHTML += '<strong class="error"><?php echo $l['communicationError'] ?></strong>';
            document.getElementById('collapsed-error').innerHTML = '<strong class="error"><?php echo $l['communicationError'] ?></strong>';
            if (msg.className) {
                msg.style.height = '40px';
            }
        }
    };
    xhr.open('GET', '?action=' + action, true);
    xhr.send(null);
};

window.onload = init;
}());
    <?php
}

// ------------------------------ utility functions ---------------------------
function OK($msg = 'OK') {
    global $l;
    $msg = $l[$msg];
    return "1|<strong class=\"confirm\">$msg</strong><br />";
}

function fail($msg) {
    global $l;
    $msg = $l[$msg];
    return "0|<strong class=\"error\">$msg</strong><br />";
}
exit;
//FILEEND?>